package com.fz.mybatis;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by webrx on 2017-08-24.
 */
public class MyBatisHelper<E> {     //工具类
    private SqlSessionFactory sf;
    private SqlSession ss;
    private Class e;
    public MyBatisHelper(){
        try {
            InputStream i= Resources.getResourceAsStream("mybatis-config.xml");
            this.sf=new SqlSessionFactoryBuilder().build(i);
            this.ss=this.sf.openSession();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public MyBatisHelper(Class e){
        try {
            InputStream i= Resources.getResourceAsStream("mybatis-config.xml");
            this.sf=new SqlSessionFactoryBuilder().build(i);
            this.ss=this.sf.openSession();
            this.e = e;
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public E getMapper(){
        return (E)this.ss.getMapper(this.e);
    }
//这个方法目前我还没看到有什么用
    public E getMapper(Class c){
        return (E)this.ss.getMapper(c);
    }

    //取得session的方法
    public SqlSession getSession() {
        return this.ss;
    }



   public void test(){
        System.out.println(e);
   }





    public void close(){
        if(this.ss!=null){
            this.ss.commit();
            this.ss.close();
        }
    }
}
